<template>
  <div class="dashboard-container">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="data-card">
          <div class="data-header">
            <div class="data-title">用户总数</div>
            <el-icon class="data-icon"><User /></el-icon>
          </div>
          <div class="data-content">
            <div class="data-number">{{ stats.totalUsers || 0 }}</div>
            <div class="data-trend" :class="{ 'is-increase': stats.userTrend > 0 }">
              <span>今日新增 {{ stats.newUsers || 0 }}</span>
              <el-icon><ArrowUp v-if="stats.userTrend > 0" /><ArrowDown v-else /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="data-card">
          <div class="data-header">
            <div class="data-title">视频总数</div>
            <el-icon class="data-icon"><VideoCamera /></el-icon>
          </div>
          <div class="data-content">
            <div class="data-number">{{ stats.totalVideos || 0 }}</div>
            <div class="data-trend" :class="{ 'is-increase': stats.videoTrend > 0 }">
              <span>今日新增 {{ stats.newVideos || 0 }}</span>
              <el-icon><ArrowUp v-if="stats.videoTrend > 0" /><ArrowDown v-else /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="data-card">
          <div class="data-header">
            <div class="data-title">帖子总数</div>
            <el-icon class="data-icon"><Document /></el-icon>
          </div>
          <div class="data-content">
            <div class="data-number">{{ stats.totalPosts || 0 }}</div>
            <div class="data-trend" :class="{ 'is-increase': stats.postTrend > 0 }">
              <span>今日新增 {{ stats.newPosts || 0 }}</span>
              <el-icon><ArrowUp v-if="stats.postTrend > 0" /><ArrowDown v-else /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="data-card">
          <div class="data-header">
            <div class="data-title">评论总数</div>
            <el-icon class="data-icon"><ChatDotRound /></el-icon>
          </div>
          <div class="data-content">
            <div class="data-number">{{ stats.totalComments || 0 }}</div>
            <div class="data-trend" :class="{ 'is-increase': stats.commentTrend > 0 }">
              <span>今日新增 {{ stats.newComments || 0 }}</span>
              <el-icon><ArrowUp v-if="stats.commentTrend > 0" /><ArrowDown v-else /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表和列表区域 -->
    <el-row :gutter="20" class="dashboard-content">
      <!-- 左侧图表 -->
      <el-col :xs="24" :lg="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>数据趋势</span>
              <el-radio-group v-model="chartType" size="small">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" v-loading="loadingChart">
            <!-- 这里将使用 ECharts 展示数据趋势 -->
            <div ref="chartRef" style="width: 100%; height: 350px;"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧活动日志 -->
      <el-col :xs="24" :lg="8">
        <el-card class="activity-card">
          <template #header>
            <div class="card-header">
              <span>最近活动</span>
              <el-button text>查看全部</el-button>
            </div>
          </template>
          <div class="activity-list" v-loading="loadingActivities">
            <el-timeline>
              <el-timeline-item
                v-for="activity in activities"
                :key="activity._id"
                :timestamp="formatDate(activity.createdAt)"
                :type="getActivityType(activity.type)"
              >
                {{ activity.description }}
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { User, VideoCamera, Document, ChatDotRound, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import axios from '@/services/axios'
import { formatDate } from '@/utils/formatters'

// 统计数据
const stats = ref({
  totalUsers: 0,
  newUsers: 0,
  userTrend: 0,
  totalVideos: 0,
  newVideos: 0,
  videoTrend: 0,
  totalPosts: 0,
  newPosts: 0,
  postTrend: 0,
  totalComments: 0,
  newComments: 0,
  commentTrend: 0
})

// 图表相关
const chartRef = ref(null)
const chartType = ref('week')
const loadingChart = ref(true)
let chart = null

// 活动日志
const activities = ref([])
const loadingActivities = ref(true)

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await axios.get('/api/admin/stats')
    stats.value = response.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取图表数据
const fetchChartData = async () => {
  loadingChart.value = true
  try {
    const response = await axios.get(`/api/admin/stats/trend?type=${chartType.value}`)
    initChart(response.data)
  } catch (error) {
    console.error('获取趋势数据失败:', error)
  } finally {
    loadingChart.value = false
  }
}

// 初始化图表
const initChart = (data) => {
  if (!chartRef.value) return

  // 确保在组件挂载后再初始化图表
  nextTick(() => {
    if (!chart) {
      chart = echarts.init(chartRef.value)
      // 监听窗口大小变化
      window.addEventListener('resize', handleResize)
    }

    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['用户', '视频', '帖子', '评论']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: data.dates || []
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '用户',
          type: 'line',
          data: data.users || [],
          smooth: true
        },
        {
          name: '视频',
          type: 'line',
          data: data.videos || [],
          smooth: true
        },
        {
          name: '帖子',
          type: 'line',
          data: data.posts || [],
          smooth: true
        },
        {
          name: '评论',
          type: 'line',
          data: data.comments || [],
          smooth: true
        }
      ]
    }

    chart.setOption(option)
  })
}

// 获取活动日志
const fetchActivities = async () => {
  loadingActivities.value = true
  try {
    const response = await axios.get('/api/admin/activities')
    activities.value = response.data
  } catch (error) {
    console.error('获取活动日志失败:', error)
  } finally {
    loadingActivities.value = false
  }
}

// 获取活动类型
const getActivityType = (type) => {
  const typeMap = {
    user: 'primary',
        video: 'success',
    post: 'warning',
    comment: 'info'
  }
  return typeMap[type] || 'info'
}

// 监听图表类型变化
watch(chartType, () => {
  fetchChartData()
})

// 监听窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

onMounted(async () => {
  try {
    await Promise.all([
      fetchStats(),
      fetchChartData(),
      fetchActivities()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
})

onUnmounted(() => {
  if (chart) {
    window.removeEventListener('resize', handleResize)
    chart.dispose()
    chart = null
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.data-card {
  margin-bottom: 20px;
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.data-title {
  font-size: 16px;
  color: #909399;
}

.data-icon {
  font-size: 24px;
  color: #409eff;
}

.data-content {
  display: flex;
  flex-direction: column;
}

.data-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.data-trend {
  font-size: 14px;
  color: #f56c6c;
  display: flex;
  align-items: center;
  gap: 4px;
}

.data-trend.is-increase {
  color: #67c23a;
}

.dashboard-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  min-height: 350px;
}

.activity-list {
  height: 350px;
  overflow-y: auto;
}

.activity-list :deep(.el-timeline-item__content) {
  color: #606266;
}

.activity-list :deep(.el-timeline-item__timestamp) {
  color: #909399;
  font-size: 12px;
}
</style>